#include "warehouse.h"
#include <stdlib.h>
#include <string.h>
#include <stdio.h>



/*
** 功能：创建货物节点
** id		货物唯一ID
** name		货物名称
** quantity	数量
*/ 
ItemNode *create_node(int id, const char *name, int quantity)
{
	ItemNode *new = (ItemNode *)malloc(sizeof(ItemNode));
	if(new == NULL)
	{
		perror("内存分配失败\n");
		exit(1);
	}
	
	new->id = id;
	strncpy(new->name, name, sizeof(new->name));
	new->quantity = quantity;
	new->prev = new;
	new->next = new;
	
	return new;
}

/*
** 功能：创建链表
** id		货物唯一ID
** name		货物名称
** quantity	数量
*/ 
ItemNode *list_init(void)
{
	return create_node(0, " ", 0);
}


/*
** 功能：插入货物节点
** head		货物链表
** new		准备添加的货物节点
*/ 
void list_add_tail(ItemNode *head, ItemNode *new)
{
	new->next = head;
	new->prev = head->prev;
	
	head->prev->next = new;
	head->prev = new;
}


/*
** 功能：根据id删除货物节点
** head		货物链表
** new		准备添加的货物节点
*/ 
void delete_by_id(ItemNode *head, int id)
{
	ItemNode *tmp = head->next;
	
	for( ; tmp != head; tmp = tmp->next)
	{
		if( tmp->id == id )
		{
			tmp->prev->next = tmp->next;
			tmp->next->prev = tmp->prev;
			free(tmp);
			break;
		}
	}
	
	return ;
}

/*
** 功能：根据id查找货物节点
** head		货物链表
** new		准备查找的货物节点
*/ 
ItemNode *find_by_id(ItemNode *head, int id)
{
	ItemNode *tmp = head->next;
	
	for( ; tmp != head; tmp = tmp->next)
	{
		if( tmp->id == id )
		{
			return tmp;
		}
	}
	
	return NULL;
}



/*
** 功能：遍历货物
** head		货物链表
*/ 
void list_for_each(ItemNode *head)
{
	ItemNode *tmp = head->next;
	
	printf("\n-%8s\t%-50s\t%-8s\n", "货物编号", "货物名称", "货物数量");
	printf("%s\n", "---------------------------------------------------------------------");
	for( ; tmp != head; tmp = tmp->next)
	{
		printf("-%08d\t%-50s\t%-8d\n", tmp->id, tmp->name, tmp->quantity);
	}	
}



/*
** 功能：从文件加载数据
** filename		文件名字
*/ 
void file_load_data(ItemNode *head, const char *filename)
{
	FILE *fp = fopen(filename, "rb");
	if(fp == NULL)
	{
		perror("file_load_data fail");
		return ;
	}

	// 从文件读取数据，加载到链表
	ItemNode tmp; 
	while( fread(&tmp, sizeof(ItemNode), 1, fp) == 1 )
	{
		ItemNode *new = create_node(tmp.id, tmp.name, tmp.quantity);
		list_add_tail(head, new);
	}
	
	fclose(fp);
}

/*
** 功能：保存数据到文件
** filename		文件名字
*/ 
void file_save_data(ItemNode *head, const char *filename)
{
	FILE *fp = fopen(filename, "wb");
	if(fp == NULL)
	{
		perror("file_save_data fail");
		return ;
	}
	
	// 把链表数据遍历，写入文件
	ItemNode *tmp = head->next;
	
	for( ; tmp != head; tmp = tmp->next)
	{
		fwrite(tmp, sizeof(ItemNode), 1, fp);
	}	
	
	fclose(fp);
}


